// pages/print/document/document.js
var utils = require("../../../utils/utils.js");
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    piclist: [],
    chooseImageArray: [],
    fpInfo: [],
    firstOpen: 0,
    inter: ''
  },
  //获取发票图片
  getFP(a, b, d, id) {
    var that = this;
    utils.request('convert/getElectronicInvoice', {
      'cardId': a,
      'encryptCode': b
    }, function (res) {
      //   wx.hideLoading()
      that.selectComponent("#loading").hideLoadingCus();
      if (res.data.code == 200) {
        wx.navigateTo({
          url: '../list/list?code=' + d + '&name=' + res.data.data.oriName + '&path=' + res.data.data.fileUrl + '&pageNum=1&fileUrl=' + res.data.data.fileUrl + '&serviceMainId=' + that.data.serviceMainId + '&serviceSubtypeId=' + id + '&tagFloor=' + that.data.tagFloor + '&color=2'
        })
      } else {
        utils.toast(res.data.msg)
      }
    })
  },
  changeIndex(e) {
    // qq.chooseExternalFile({
    //   from:'Weiyun',
    //   success(res){
    //     qq.showModal({
    //       title:'成功',
    //       content:JSON.stringify(res)
    //     })
    //   },
    //   fail(res){
    //     qq.showModal({
    //       title:'',
    //       content:JSON.stringify(res)
    //     })
    //   }
    // })
    // return false;
    var code = e.currentTarget.dataset.code;
    var url = e.currentTarget.dataset.url;
    var id = e.currentTarget.dataset.id;
    var status = e.currentTarget.dataset.status;
    var quickUrl = e.currentTarget.dataset.quickurl;
    var that = this;
    if (status == '-1') {
      utils.toast('项目装修中，敬请期待')
      return false;
    }
    if (utils.is_define(quickUrl)) {

      wx.navigateTo({
        url: quickUrl
      })
      return false;
    }
    if (utils.is_define(url)) {
      wx.navigateTo({
        url: url + '?code=' + code + '&serviceMainId=' + that.data.serviceMainId + '&serviceSubtypeId=' + id + '&tagFloor=' + that.data.tagFloor,
      })
      return false;
    }
    if (code == 'document_QQDocument') {
      wx.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ['doc', 'xls', 'ppt', 'docx', 'xlsx', 'pptx', 'pdf'],
        success(res) {
          var reg = /^.*\.(?:xls|xlsx)$/i;
          if (reg.test(res.tempFiles[0].name)) {
            //excel
            that.excelTpdf(res.tempFiles[0].path, res.tempFiles[0].name, code, id)
          } else {
            //非excel
            //  wx.showLoading()
            that.selectComponent("#loading").showLoadingCus('加密上传中');
            that.settingDoc(res.tempFiles[0].path, res.tempFiles[0].name, code, id)
          }

        }
      })
    }
    if (code == 'document_wpsDocument') {
      wx.navigateTo({
        url: '/pages/print/kdocs/kdocs?code=' + code + '&serviceMainId=' + that.data.serviceMainId + '&serviceSubtypeId=' + id + '&tagFloor=' + that.data.tagFloor,
      })
    }
    if (code == 'document_invoice') {
      wx.chooseInvoice({
        success: (result) => {
          var str = JSON.parse(result.invoiceInfo)
          that.setData({
            fpInfo: str
          })
          if (utils.is_define(str)) {
            // wx.showLoading()
            that.selectComponent("#loading").showLoadingCus();
            that.getFP(that.data.fpInfo[0].card_id, that.data.fpInfo[0].encrypt_code, code, id)
          }
        },
      })
    }
    if (code == 'document_weChatDocument') {
      wx.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ['doc', 'xls', 'ppt', 'docx', 'xlsx', 'pptx', 'pdf'],
        success(res) {
          var reg = /^.*\.(?:xls|xlsx)$/i;
          if (reg.test(res.tempFiles[0].name)) {
            //excel
            that.excelTpdf(res.tempFiles[0].path, res.tempFiles[0].name, code, id)
          } else {
            //非excel
            //  wx.showLoading()
            that.selectComponent("#loading").showLoadingCus();
            that.settingDoc(res.tempFiles[0].path, res.tempFiles[0].name, code, id)
          }

        }
      })
    }
    if (code == 'document_localDocument') {
      wx.navigateTo({
        url: '../local/local?code=' + code + '&serviceMainId=' + that.data.serviceMainId + '&serviceSubtypeId=' + id + '&tagFloor=' + that.data.tagFloor,
      })
    }
    if (code == 'document_zip') {
      wx.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ['rar', '7z', 'zip'],
        success(res) {
          //   wx.showLoading()
          that.selectComponent("#loading").showLoadingCus('解压中');
          that.delZip(res.tempFiles[0].path, res.tempFiles[0].name, code, id)
        }
      })
    }
    if (code == 'document_imagesBatch') {
      //选择图片，批量图片上传转文档
      wx.showActionSheet({
        itemList: ['相册', '从QQ会话选择'],
        success(res) {
          if (res.tapIndex == 0) {
            that.getPhoto('album', code, id);
          }
          if (res.tapIndex == 1) {
            that.choosePicFormChat(code, id);
          }
        },
        fail(res) {

        }
      })
    }

  },
  //拍照调取相册
  getPhoto(type, code, id) {
    var that = this;
    wx.chooseImage({
      count: 9,
      sizeType: ['original'],
      sourceType: [type],
      success(res) {
        that.setData({
          chooseImageArray: res.tempFilePaths
        })
        //轮巡判断上传
        that.uploadFileImg(that.data.chooseImageArray[0], 0, code, id);
      }
    })
  },
  choosePicFormChat(code, id) {
    var that = this;
    wx.chooseMessageFile({
      count: 9,
      type: 'image',
      success(res) {
        var array = [];
        for (var i = 0; i < res.tempFiles.length; i++) {
          array.push(res.tempFiles[i].path)
        }
        that.setData({
          chooseImageArray: array
        })
        //轮巡判断上传
        that.uploadFileImg(that.data.chooseImageArray[0], 0, code, id);
      }
    })
  },
  //上传图片
  uploadFileImg(url, index, code, id) {
    var that = this;
    var imgs = that.data.chooseImageArray;
    var indexs = parseInt(index) + 1;
    var str = '上传 ' + indexs + '/' + that.data.chooseImageArray.length + '张';
    that.selectComponent("#loading").showLoadingCus(str);
    utils.uploadfile(url, url, '', '', '', function (res) {
      console.log(res)
      var data = JSON.parse(res.data)
      console.log(data)
      that.selectComponent("#loading").hideLoadingCus();
      if (data.code == 200) {
        var imgurl = '';
        if (data.data.width > data.data.height) {
          imgurl = data.data.printUrl + '?x-oss-process=image/resize,w_2400,m_lfit/rotate,90/quality,Q_100/auto-orient,0/format,jpg';
        } else {
          imgurl = data.data.printUrl + '?x-oss-process=image/quality,Q_100/auto-orient,0/format,jpg';
        }
        var obj = that.data.piclist;
        obj.push(imgurl);
        that.setData({
          piclist: obj
        })
        if (index == imgs.length - 1) {
          that.setData({
            chooseImageArray: []
          })
          that.selectComponent("#loading").hideLoadingCus();
          that.selectComponent("#loading").showLoadingCus('转换中');
          that.transPdf(code, id)
        } else {
          that.uploadFileImg(imgs[index + 1], index + 1, code, id)
        }
      } else if (data.code == -200) {
        utils.toast(data.msg);
        if (index == imgs.length - 1) {
          that.setData({
            chooseImageArray: []
          })
          that.selectComponent("#loading").hideLoadingCus();
        } else {
          that.uploadFileImg(imgs[index + 1], index + 1, code, id)
        }
      } else {
        utils.toast(data.msg);
        that.setData({
          piclist: [],
          chooseImageArray: []
        })
      }
    })
  },
  transPdf(code, id) {
    var that = this;
    var str = that.data.piclist.join(';')
    utils.request('convert/mergePhotos', { 'urls': str }, function (res) {
      that.selectComponent("#loading").hideLoadingCus();
      if (res.data.code == 200) {
        that.setData({
          piclist: []
        })
        wx.navigateTo({
          url: '../list/list?code=' + code + '&name=' + res.data.data.localName + '&path=' + res.data.data.printUrl + '&pageNum=' + res.data.data.pageTotal + '&fileUrl=' + res.data.data.printUrl + '&serviceMainId=' + that.data.serviceMainId + '&serviceSubtypeId=' + id + '&tagFloor=' + that.data.tagFloor + '&orientation=' + res.data.data.orientation
        })
      } else {
        that.setData({
          piclist: []
        })
        utils.toast(res.data.msg)
      }
    })
  },
  //压缩包处理
  delZip(path, name, code, id) {
    var that = this;
    utils.uploadZip(path, function (res) {
      var data = JSON.parse(res.data).data
      if (JSON.parse(res.data).code == -200) {
        // wx.hideLoading()
        that.selectComponent("#loading").hideLoadingCus();
        wx.navigateTo({
          url: '/pages/print/zipPage/zipPage?succ=0&name=' + name + '&code=' + code + '&serviceMainId=' + that.data.serviceMainId + '&serviceSubtypeId=' + id + '&tagFloor=' + that.data.tagFloor,
        })
      } else {
        var list = escape(JSON.stringify(data))
        // wx.hideLoading()
        that.selectComponent("#loading").hideLoadingCus();
        wx.navigateTo({
          url: '/pages/print/zipPage/zipPage?succ=1&list=' + list + '&code=' + code + '&serviceMainId=' + that.data.serviceMainId + '&serviceSubtypeId=' + id + '&tagFloor=' + that.data.tagFloor + '&name=' + name
        })
      }
    })
  },
  //文档处理
  settingDoc(path, name, code, id) {
    var that = this;
    utils.uploadfile(path, name, '', '', '', function (res) {
      var data = JSON.parse(res.data).data
      // wx.hideLoading()
      that.selectComponent("#loading").hideLoadingCus();
      wx.navigateTo({
        url: '../list/list?code=' + code + '&name=' + data.localName + '&path=' + data.printUrl + '&pageNum=' + data.pageTotal + '&fileUrl=' + data.fileUrl + '&serviceMainId=' + that.data.serviceMainId + '&serviceSubtypeId=' + id + '&tagFloor=' + that.data.tagFloor + '&orientation=' + data.orientation
      })
    })
  },
  //excel转pdf
  excelTpdf(path, name, code, id) {
    var that = this;
    // wx.showLoading()
    that.selectComponent("#loading").showLoadingCus('转换中');
    utils.uploadfileExcel(path, name, function (res) {
      var data = JSON.parse(res.data).data
      //    wx.hideLoading()
      that.selectComponent("#loading").hideLoadingCus();
      wx.navigateTo({
        url: '/pages/print/chooseSheet/chooseSheet?list=' + escape(JSON.stringify(data)) + '&serviceMainId=' + that.data.serviceMainId + '&serviceSubtypeId=' + id + '&tagFloor=' + that.data.tagFloor + '&code=' + code,
      })
    })
  },
  getIndex() {
    var that = this;
    utils.request('serviceItem/serviceItemLists/' + that.data.serviceMainId, {}, function (res) {
      if (res.data.code == 200) {
        var docArray = [];
        docArray = res.data.data
        that.setData({
          list: docArray
        })
      } else {
        utils.toast(res.data.msg)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (utils.is_define(options.sn)) {
      wx.setStorageSync('machineQrCode', options.sn)
    }
    this.setData({
      tagFloor: options.code,
      serviceMainId: options.serviceMainId
    })
    this.getIndex()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.firstOpen == 1) {
      this.getIndex();
    } else {
      this.setData({
        firstOpen: 1
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})